package main

import (
	"fmt"
	"math/rand"
	"strconv"
	"time"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

type Product struct {
	ID    uint `gorm:"AUTO_INCREMENT"`
	Code  string
	Price int
}

func addproduct(db *gorm.DB, p *Product) {
	//db.NewRecord(p)
	db.Create(p)
	//s = <-1
	fmt.Println(p.Code)
}

func main() {
	var done = make(chan int)
	db, err := gorm.Open("mysql", "root:root@tcp(192.168.1.104:3306)/yyu")
	if err != nil {
		panic("failed to connect database")
	}
	defer db.Close()

	// 自动迁移表，生成的表名为 products
	//db.AutoMigrate(p)
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i <= 10; i++ {
		var p *Product = new(Product)
		p.Code = "c" + strconv.Itoa(i)
		p.Price = r.Intn(100)

		go addproduct(db, p)
		//time.Sleep(time.Second * 1)
	}

	done <- 1
	close(done)
	// Create

	// Read
	//	var product Product
	//	db.First(&product, 1)                   // find product with id 1
	//	db.First(&product, "code = ?", "L1212") // find product with code l1212

	//	// Update
	//	db.Model(&product).Update("Price", 2000)

	//Delete
	//db.Delete(&product)

}
